package com.zhm.langchain4j;

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.ConfigChangeEvent;
import com.alibaba.nacos.api.config.ConfigChangeItem;
import com.alibaba.nacos.client.config.listener.impl.AbstractConfigChangeListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.endpoint.event.RefreshEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Slf4j
@Component
public class NacosConfigRefreshListener implements InitializingBean {

    @Autowired
    private  NacosConfigManager nacosConfigManager;

    @Override
    public void afterPropertiesSet() throws Exception {
        AbstractConfigChangeListener listener =
                new AbstractConfigChangeListener() {
                    @Override
                    public void receiveConfigChange(ConfigChangeEvent event) {
                        Collection<ConfigChangeItem> changeItems = event.getChangeItems();
                        log.info(changeItems.toString());
                    }
                };
        this.nacosConfigManager
                .getConfigService()
                .addListener("hero-gateway-config.yaml", "DEFAULT_GROUP", listener);
    }

    @EventListener(RefreshEvent.class)
    public void onRefresh(RefreshEvent event) {
        // 配置文件发生变化时执行的逻辑
        System.out.println("Nacos config has been refreshed.");
        // 你可以在这里重新加载资源或执行其他逻辑
    }
}
